#!/usr/bin/env python
# -*- coding: utf-8 -*-

import configparser
import os
from typing import Dict, Any

class Config:
    def __init__(self, config_file: str = 'config.ini'):
        self.config_file = config_file
        self.config: Dict[str, Any] = {
            'node_id': '',  # 节点唯一标识
            'stun_server': 'stun.l.google.com:19302',  # STUN服务器地址
            'virtual_network': '10.0.0.0/24',  # 虚拟网络地址段
            'virtual_ip': '',  # 本节点虚拟IP
            'encryption_key': '',  # 加密密钥
            'remote_node': {  # 远程节点信息
                'id': '',
                'virtual_ip': ''
            },
            'log_level': 'INFO',
            'log_file': 'p2p_vpn.log'
        }

    def load(self) -> None:
        """从配置文件加载配置"""
        if os.path.exists(self.config_file):
            try:
                config_parser = configparser.ConfigParser()
                config_parser.read(self.config_file, encoding='utf-8')
                
                # 加载必需配置
                if 'required' in config_parser:
                    for key in ['node_id', 'virtual_ip', 'virtual_network']:
                        if key in config_parser['required']:
                            self.config[key] = config_parser['required'][key]
                
                # 加载远程节点配置
                if 'remote_node' in config_parser:
                    self.config['remote_node'] = {
                        'id': config_parser['remote_node'].get('id', ''),
                        'virtual_ip': config_parser['remote_node'].get('virtual_ip', '')
                    }
                
                # 加载可选配置
                if 'optional' in config_parser:
                    for key in ['stun_server', 'log_level', 'log_file']:
                        if key in config_parser['optional']:
                            self.config[key] = config_parser['optional'][key]
            except Exception as e:
                print(f'加载配置文件失败: {e}')

    def save(self) -> None:
        """保存配置到文件"""
        try:
            config_parser = configparser.ConfigParser()
            
            # 保存必需配置
            config_parser['required'] = {
                'node_id': self.config['node_id'],
                'virtual_ip': self.config['virtual_ip'],
                'virtual_network': self.config['virtual_network']
            }
            
            # 保存远程节点配置
            config_parser['remote_node'] = {
                'id': self.config['remote_node']['id'],
                'virtual_ip': self.config['remote_node']['virtual_ip']
            }
            
            # 保存可选配置
            config_parser['optional'] = {
                'stun_server': self.config['stun_server'],
                'log_level': self.config['log_level'],
                'log_file': self.config['log_file']
            }
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                config_parser.write(f)
        except Exception as e:
            print(f'保存配置文件失败: {e}')

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        return self.config.get(key, default)

    def set(self, key: str, value: Any) -> None:
        """设置配置项"""
        self.config[key] = value

    def update(self, config_dict: Dict[str, Any]) -> None:
        """批量更新配置"""
        self.config.update(config_dict)

# 全局配置实例
config = Config()